package com.lx.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.lx.mall.search.consts.SearchConstant;
import com.lx.mall.search.domain.EsProduct;
import com.lx.mall.search.service.IPreferredMallSearchService;
import com.lx.mall.search.vo.ESRequestParam;
import com.lx.mall.search.vo.ESResponseResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.text.Highlighter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wcy
 */
@Service
public class PreferredMallSearchService implements IPreferredMallSearchService {


    @Qualifier("restHighLevelClient")
    @Autowired
    private RestHighLevelClient esClient;

    @Override
    public ESResponseResult search(ESRequestParam param) {

        try {

            //1、构建检索对象-封装请求相关参数信息
            SearchRequest searchRequest = startBuildRequestParam(param);

            //2、进行检索操作
            SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println("response:"+response);
            return startBuildResponseResult(response,param);

        }catch (Exception e){
            e.printStackTrace();

        }
        return null;
    }

    /**
     * 封装请求参数信息
     * 关键字查询、根据属性、分类、品牌、价格区间、是否有库存等进行过滤、分页、高亮、以及聚合统计品牌分类属性
     *
     */
    private SearchRequest startBuildRequestParam(ESRequestParam param){

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();


        /**
         * 关键字查询、根据属性、分类、品牌、价格区间、是否有库存等进行过滤、分页、高亮、以及聚合统计品牌分类属性
         */
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //1.根据关键字匹配查询
        if(!StringUtils.isEmpty(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.multiMatchQuery(param.getKeyword(),"name","keywords","subTitle"));
        }
        //2.根据分类ID过滤
        if(!StringUtils.isEmpty(param.getCategoryId())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("categoryId",param.getCategoryId()));
        }
        //3.根据分类ID过滤
        if(!StringUtils.isEmpty(param.getBrandId())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brandId",param.getBrandId()));
        }
        //4.根据属性ID过滤
         //attrs=1_白色&2_4核
        if(!StringUtils.isEmpty(param.getAttrs())){
            param.getAttrs().forEach(item -> {
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                //attrs=1_64G
                String[] s = item.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");//这个属性检索用的值
                boolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolQuery.must(QueryBuilders.termQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", boolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            });
        }
        //5.是否有库存
        if(null != param.getHasStock()){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()==1));
        }

        //6.根据价格过滤
        if(!StringUtils.isEmpty(param.getPrice())){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price");
            String[] price = param.getPrice().split("_");
            if (price.length == 2){
                //price: _5000
                if (param.getPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(price[1]);
                }else {
                    //price: 1_5000
                    rangeQueryBuilder.gte(price[0]).lte(price[1]);
                }
            }else if(price.length == 1){
                //price: 1_
                if (param.getPrice().endsWith("_")) {
                    rangeQueryBuilder.gte(price[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        //封装所有查询条件
        searchSourceBuilder.query(boolQueryBuilder);

        //高亮、排序、分页操作
        //页面传入的参数值形式 sort=price_asc/desc
        if(!StringUtils.isEmpty(param.getSort())){
            String sort = param.getSort();
            String[] sortFileds = sort.split("_");
            if(!StringUtils.isEmpty(sortFileds[0])){
                SortOrder sortOrder = "asc".equalsIgnoreCase(sortFileds[1]) ? SortOrder.ASC : SortOrder.DESC;
                searchSourceBuilder.sort(sortFileds[0], sortOrder);
            }
        }
        //分页
        searchSourceBuilder.from((param.getPageNum()-1)* SearchConstant.PAGE_SIZE);
        searchSourceBuilder.size(SearchConstant.PAGE_SIZE);
        //高亮提示
        if(!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        //聚合操作  按照品牌/品目/属性进行分组
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId");
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName"));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg"));

        searchSourceBuilder.aggregation(brandAgg);

        //聚合操作  按照品目进行分组
        TermsAggregationBuilder categoryAgg = AggregationBuilders.terms("category_agg").field("categoryId");
        categoryAgg.subAggregation(AggregationBuilders.terms("category_name_agg").field("categoryName"));
        searchSourceBuilder.aggregation(categoryAgg);
        //聚合操作  按照属性进行分组
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        //按照id分组
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attrAgg.subAggregation(attrIdAgg);
        //2.1.1 在每个属性ID下，按照属性名进行聚合
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName");
        attrIdAgg.subAggregation(attrNameAgg);
        //2.1.1 在每个属性ID下，按照属性值进行聚合
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue");
        attrIdAgg.subAggregation(attrValueAgg);
        System.out.println("构建的DSL语句 {}:"+ searchSourceBuilder.toString());
        searchSourceBuilder.aggregation(attrAgg);
        SearchRequest searchRequest = new SearchRequest(new String[]{SearchConstant.INDEX_NAME}, searchSourceBuilder);
        return searchRequest;

    }
    /**
     * 封装查询到的结果信息
     * 关键字查询、根据属性、分类、品牌、价格区间、是否有库存等进行过滤、分页、高亮、以及聚合统计品牌分类属性
     */
    private ESResponseResult startBuildResponseResult(SearchResponse response, ESRequestParam param){

        ESResponseResult result = new ESResponseResult();

        List<EsProduct> esModels = new ArrayList<>();

        //1、获取查询到的商品信息
        SearchHits hits = response.getHits();

        //1.封装命中的产品信息
        if (hits.getHits() != null && hits.getHits().length > 0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                EsProduct esModel = JSON.parseObject(sourceAsString, EsProduct.class);

                //2.1 判断是否按关键字检索，若是就显示高亮，否则不显示
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    //2.2 拿到高亮信息显示标题
                    HighlightField name = hit.getHighlightFields().get("name");
                    //2.3 判断name中是否含有查询的关键字(因为是多字段查询，因此可能不包含指定的关键字，假设不包含则显示原始name字段的信息)
                    String nameValue = name!=null ? name.getFragments()[0].string() : esModel.getName();
                    esModel.setName(nameValue);
                }
                esModels.add(esModel);
            }
            result.setProducts(esModels);
        }

        //3、当前商品涉及到的所有品牌信息，小米手机和小米电脑都属于小米品牌，过滤重复品牌信息
        List<ESResponseResult.BrandVo> brandVos = new ArrayList<>();
        //获取到品牌的聚合
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        ESResponseResult.BrandVo brandVo;
        for(Terms.Bucket bucket : brandAgg.getBuckets()){
                brandVo = new ESResponseResult.BrandVo();

            //获取品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            //获取品牌的名字
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //获取品牌的LOGO
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            System.out.println("brandId:"+brandId+"brandName:"+brandName+"brandImg");
            brandVos.add(brandVo);
        }
        System.out.println("brandVos.size:"+brandVos.size());
        result.setBrands(brandVos);
        //4、当前商品相关的所有类目信息
        //获取到分类的聚合
        List<ESResponseResult.CategoryVo> categoryVos = new ArrayList<>();
        ESResponseResult.CategoryVo categoryVo;
        ParsedLongTerms categoryAgg = response.getAggregations().get("category_agg");
        ParsedStringTerms categoryNameAgg;
        long categoryId;
        for(Terms.Bucket bucket : categoryAgg.getBuckets()){
            categoryVo = new   ESResponseResult.CategoryVo();
            //获取品牌的id
            categoryId = bucket.getKeyAsNumber().longValue();
            categoryVo.setCategoryId(categoryId);
            categoryNameAgg = bucket.getAggregations().get("category_name_agg");
            String categoryName = categoryNameAgg.getBuckets().get(0).getKeyAsString();
            categoryVo.setCategoryName(categoryName);
            categoryVos.add(categoryVo);

        }
        result.setCategorys(categoryVos);

        //5、获取商品相关的所有属性信息
        List<ESResponseResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrsAgg = response.getAggregations().get("attr_agg");

        ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attr_id_agg");

        ESResponseResult.AttrVo attrVo;
        long attrId;
        ParsedStringTerms attrNameAgg;
        String attrName;
        ParsedStringTerms attrValueAgg;
        for(Terms.Bucket bucket : attrIdAgg.getBuckets()){
            attrVo = new ESResponseResult.AttrVo();
            attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            attrName= attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValue = new ArrayList<>();
            for(Terms.Bucket attrValueBucket : attrValueAgg.getBuckets()){
                attrValue.add(attrValueBucket.getKeyAsString());
            }
            attrVo.setAttrValue(attrValue);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        //6、进行分页操作
        result.setPageNum(param.getPageNum());
        //获取总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //计算总页码
        int totalPages = (int) total % SearchConstant.PAGE_SIZE == 0 ?
                (int) total / SearchConstant.PAGE_SIZE : ((int) total / SearchConstant.PAGE_SIZE + 1);
        result.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        return result;

    }
}
